package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"goods/goodsrpc/goodsrpc"
	"goods/goodsrpc/internal/svc"
	"goods/model/mysql"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsAddLogic) GoodsAdd(in *goodsrpc.GoodsAddRequest) (*goodsrpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line
	begin := mysql.DB.Debug().Begin()

	var class mysql.Class
	err := begin.Where("name = ?", in.ClassName).Find(&class).Error
	if err != nil {
		begin.Rollback()
		return nil, fmt.Errorf("查询分类失败")
	}
	if class.ID == 0 {
		class = mysql.Class{
			Name: in.ClassName,
		}
		err := begin.Create(&class).Error
		if err != nil {
			begin.Rollback()
			return nil, fmt.Errorf("分类添加失败")
		}
	}

	var brand mysql.Brand
	begin.Where("name = ?", in.BrandName).Find(&brand)
	if brand.ID == 0 {
		brand = mysql.Brand{
			Name: in.BrandName,
		}
		err := begin.Create(&brand).Error
		if err != nil {
			begin.Rollback()
			return nil, fmt.Errorf("品牌数据添加失败")
		}
		begin.Commit()
	}

	var goods mysql.Goods
	goods = mysql.Goods{
		Name:    in.Name,
		Image:   in.Image,
		Price:   float64(in.Price),
		BrandId: int64(brand.ID),
		ClassId: int64(class.ID),
	}
	err = begin.Create(&goods).Error
	if err != nil {
		begin.Rollback()
		return nil, fmt.Errorf("添加失败")
	}
	begin.Commit()
	return &goodsrpc.GoodsAddResponse{
		GoodsId: int64(goods.ID),
	}, nil
}
